<?php

namespace App\Http\Validate\OpenShop\StartBusiness;

use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Http\Validate\AbstractBaseValidate;
use App\Models\OpenShop\StartBusiness\OpenShopStartBusinessModel;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\MessageBag;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * [ 订单业务验证 ] - 校验规则
 *
 * @OpenShopUserContractValidate
 * @package App\Http\Controllers
 * @date 2022/03/01 02:35:56
 * @author GreenLeaf <786407418@qq.com>
 */
class StartBusinessValidate extends AbstractBaseValidate
{
    public function registerValidateRules(): void
    {
        // TODO: Implement registerValidateRules() method.
        Validator::extend('subsetValidate',
            function ($attribute, $value, $parameters, \Illuminate\Validation\Validator $validator) {
                $validator->requireParameterCount(1, $parameters, 'compareDateTime');
                $selectOption = unserialize($parameters[0]);
                return count(array_unique(array_merge($selectOption, $value))) == count($selectOption);
            }, '参数不合法');
    }

    public function getAttributes(): array
    {
        // TODO: Implement getAttributes() method.
        return [
            "orderNo"      => "签约订单号",
            "staffCount"   => "员工数",
            "monthlyWages" => "月工资金额",
            'eatInTotal'   => '堂食位数',
        ];
    }

    public function getMessages(): array
    {
        // TODO: Implement getMessages() method.
        return [
        ];
    }

    private array $rules = [];

    public function getRules(bool $withoutRequired = false): array
    {
        if ($this->rules) {
            return $this->rules;
        }

        // TODO: Implement getRules() method.
        $arr = [
            'page'                      => 'integer|between:0,3',
            "eatInTotal"                => "bail|required|int|min:0|max:255",
            "hasMonitorUint"            => "bail|required|int|in:" . enumTransToRules(OpenShopStartBusinessModel::MONITOR_UNIT_MAP),
            "hasRight"                  => "bail|required|int|in:" . enumTransToRules(OpenShopStartBusinessModel::RIGHT_MAP),
            "rightDetail"               => 'exclude_unless:hasRight,' . OpenShopStartBusinessModel::HAS_RIGHT_YES . "|required|string|min:0",
            "sellChannel"               => "bail|required|array|subsetValidate:" . serialize(array_keys(OpenShopStartBusinessModel::SELL_CHANNEL_MAP)),
            "employmentExperience"      => "bail|required|int|in:" . enumTransToRules(OpenShopStartBusinessModel::EMPLOYMENT_EXPERIENCE_MAP),
            "managementInput"           => "bail|required|int|in:" . enumTransToRules(OpenShopStartBusinessModel::MANAGEMENT_INPUT_TYPE_MAP),
            "degreeCooperation"         => "bail|required|int|in:" . enumTransToRules(OpenShopStartBusinessModel::DEGREE_COOPERATION_TYPE),
            "startBusinessTime"         => "bail|required|string|date_format:Y-m-d",
            "sellPriceType"             => "bail|required|int|in:" . enumTransToRules(OpenShopStartBusinessModel::SELL_PRICE_TYPE),
            "menuCategory"              => "bail|required|array|subsetValidate:" . serialize(array_keys(OpenShopStartBusinessModel::MENU_CATEGORY_TYPE)),
            "staffCount"                => "bail|required|int|min:1",
            "monthlyWages"              => "bail|required|int|min:0|max:10000000",
            "startBusinessActivityDesc" => "bail|required|string",
            "promoteChancePointDesc"    => "bail|required|string",
            "leaveBehindQuestionDesc"   => "bail|required|string",
            "startShopPic"              => "array",
            "startHotMv"                => "array",
        ];

        if (!$withoutRequired) {
            return $arr;
        }

        foreach ($arr as &$v) {
            $v = str_replace('required|', '', $v);
        }

        $this->rules = $arr;
        return $arr;
    }

    /**
     * @param array $data
     * @return MessageBag|object
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function submitValidate(array $data, bool $withoutRequired = false)
    {
        $self = self::getInstance();

        return $self->validate(
            collect($self->getRules($withoutRequired))->keys()->toArray(),
            $data,
            [
                "orderNo" => [
                    "bail",
                    "required",
                    Rule::exists("open_shop_start_business", "orderNo")
                        ->where("step", MainProcessEnum::START_BUSINESS_STAY)
                ]
            ],
            true,
            function (array $params) {
                if (isset($params["startBusinessTime"])) {
                    $params["startBusinessTime"] = strtotime($params["startBusinessTime"] ?? '');
                }

                if (isset($params["menuCategory"] )) {
                    $params["menuCategory"]      = json_encode($params["menuCategory"] ?? [], JSON_UNESCAPED_UNICODE);
                }

                if (isset($params['sellChannel'])) {
                    $params["sellChannel"]       = json_encode($params["sellChannel"] ?? [], JSON_UNESCAPED_UNICODE);
                }

                return $params;
            }
        );
    }


    /**
     * @param array $data
     * @return MessageBag|object
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function updateValidate(array $data)
    {
        $self = self::getInstance();
        return $self->validate(
            collect($self->getRules())->keys()->toArray(),
            $data,
            [
                "orderNo" => [
                    "bail",
                    "required",
                    Rule::exists("open_shop_start_business", "orderNo")
                        ->where(function ($query) {
                            $query->where("step", ">", MainProcessEnum::START_BUSINESS_STAY);
                        })
                ]
            ],
            true,
            function (array $params) {
                $params["startBusinessTime"] = strtotime($params["startBusinessTime"]);
                $params["menuCategory"]      = json_encode($params["menuCategory"], JSON_UNESCAPED_UNICODE);
                $params["sellChannel"]       = json_encode($params["sellChannel"], JSON_UNESCAPED_UNICODE);
                return $params;
            }
        );
    }

    /**
     * @param array $data
     * @return MessageBag|object
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function detailValidate(array $data)
    {
        return self::getInstance()->validate(
            ["orderNo"],
            $data,
            [
                "orderNo" => [
                    "bail",
                    "required",
                    Rule::exists("open_shop_start_business", "orderNo")
                ]
            ]
        );
    }

    /**
     * 附件校验
     *
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public static function attachValidate(array $requestParams)
    {
        return self::getInstance()->validate(
            collect(UploadFileResourceEnum::START_BUSINESS_MAP)->values()->merge(["orderNo"])->toArray(),
            $requestParams,
            [
                UploadFileResourceEnum::START_BUSINESS_MAP[UploadFileResourceEnum::START_BUSINESS_1] => "string",
//                UploadFileResourceEnum::START_BUSINESS_MAP[UploadFileResourceEnum::START_SHOP_PIC] => "array",
//                UploadFileResourceEnum::START_BUSINESS_MAP[UploadFileResourceEnum::START_HOT_MV] => "array",
            ],
            true,
            function (array $params) use ($requestParams) {
                $insertData = [];
                $uid        = getRmsUserInfoByAuth()->id;
                collect($params)->each(function ($v, $k) use (&$insertData, $requestParams, $uid) {
                    $position = array_keys(UploadFileResourceEnum::START_BUSINESS_MAP, $k)[0];
                    if (is_string($v)) {
                        array_push($insertData, [
                            "orderNo"      => $requestParams["orderNo"],
                            "position"     => $position,
                            "url"          => getPrivateFileKey($v),
                            "createdAt"    => time(),
                            "createdByUid" => $uid
                        ]);
                    }

                    if (is_array($v)) {
                        foreach ($v as $vv) {
                            array_push($insertData, [
                                "orderNo"      => $requestParams["orderNo"],
                                "position"     => $position,
                                "url"          => getPrivateFileKey($vv),
                                "createdAt"    => time(),
                                "createdByUid" => $uid
                            ]);
                        }
                    }
                });
                return $insertData;
            }
        );
    }
}
